﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Collections;

namespace LanguageStudy
{
    public class WordsHandle
    {
        private ArrayList m_alWords = new ArrayList();

        public WordsHandle()
        {
        }

        ~WordsHandle()
        {
            m_alWords.Clear();
        }

        public ArrayList ImportFile(string strFile)
        {
            try
            {
                StreamReader _srRead = new StreamReader(strFile, Encoding.Default);

                m_alWords.Clear();
                string _strWord;
                while (!_srRead.EndOfStream)
                {
                    _strWord = DecodeYouDao(_srRead.ReadLine());
                    if(_strWord != null)
                        m_alWords.Add(_strWord);
                }

                _srRead.Close();
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex);
            }

            return m_alWords;
        }

        public ArrayList RandomWords(int nNum)
        {
            ArrayList _alWordsCopy = new ArrayList(m_alWords);
            ArrayList _alReturn = new ArrayList();

            Random rand = new Random();

            int _nNum = nNum;
            if (_nNum <= 0)
                _nNum = _alWordsCopy.Count;
            while (_alWordsCopy.Count > 0 && _nNum > 0)
            {
                int _i = rand.Next() % _alWordsCopy.Count;
                _alReturn.Add(_alWordsCopy[_i]);
                _alWordsCopy.RemoveAt(_i);

                _nNum--;
            }

            return _alReturn;
        }

        public ArrayList GetWords()
        {
            return m_alWords;
        }

        private string DecodeYouDao(string strLine)
        {
            string[] _strArray;
            string _strWord;

            // 去除前后空格
            strLine = strLine.Trim();
            // 按空格拆分
            _strArray = strLine.Split(' ');

            // 项数小于2忽略
            if (_strArray.Length < 2)
                return null;

            // 第一项结尾不是","忽略
            if (_strArray[0].Substring(_strArray[0].Length - 1) != ",")
                return null;

            // 第二项为单词开始
            _strWord = _strArray[1];

            // 查看词组，并遇音标跳出
            for (int i = 2; i < _strArray.Length; i++)
            {
                if (_strArray[i] != "")
                {
                    if (_strArray[i].Substring(0, 1) == "[")
                        break;
                    else
                    {
                        _strWord += " ";
                        _strWord += _strArray[i];
                    }
                }
            }

            return _strWord;
        }
    }
}
